<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Model;

class IsEnabledRule implements ValidationRule
{
    public function __construct(
        protected string $model,
        protected string $primaryKey = 'id',
        protected string $status = 'status',
        protected ?string $fieldName = '数据对象'
    ) {
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!class_exists($this->model)) {
            $fail('模型不存在');

            return;
        }
        $model = new $this->model;
        if (!$model instanceof Model) {
            $fail('这不是一个模型');

            return;
        }

        if (!$model->where($this->primaryKey, $value)->exists()) {
            $fail($this->fieldName.'不存在');

            return;
        }

        if (!$model->where($this->primaryKey, $value)->value($this->status)) {
            $fail($this->fieldName.'不可用');
        }
    }
}
